/**
 * Shift form for AJAX form submit convenience
 * ==================================================
 * Author: lute
 * ==================================================
 * use case:
 * $('form').shiftform({
 *   loadingMessage: '加载提示',    // 可选，默认为“正在提交表单...”
 *   successMessage: '提交成功信息',   // 可选，默认为“表单提交成功”，优先显示服务器返回的成功信息
 *   failureMessage: '提交失败信息',   // 可选，默认为“表单提交失败”，优先显示服务器返回的业务失败信息
 *   errorMessage:  '提交出错信息',   //  可选，默认为“表单提交出错”，表示提交非业务出错信息
 *   beforeSubmit:    function(el) { // 通常做表单校验 },    // 可选，Ajax提交前执行函数
 *   success: function(el, backdrop, message) { // 提交成功callback },    // 可选
 *            string   selector-triggerEvent                            // 可选
 *   failure: function(el, backdrop, message) { // 提交失败callback }    // 可选
 * })
 */

!function(root, factory) {
  if(typeof define == 'function' && define.amd) {
    define(['jquery'], factory)
  } else if(typeof exports == 'object') {
    factory(require('jquery'))
  } else {
    factory(root.jQuery)
  }
}(this, function($) {
  'use strict';

  $.fn.modalsearch = function(option) {
    
    var options = $.extend({
          url: '',
          tableColumns: ['代码', '名称'],
          tableValues: ['code', 'name'],
          displayValues: ['code', 'name'],
          values: ['id'],
          failureMessage: '表单查询失败',
          errorMessage: '表单查询出错',
          beforeSubmit: null,
          success: null,
          failure: null
        },option)
    
    bindOpen(this);
        
    // 打开弹窗
    function bindOpen(el) {
      
      $(el).on("click", function(e){
        
        e.preventDefault();
        
        options.url = Object.prototype.toString.call(options.url) === '[object Function]' ? options.url() : options.url;
        
        var $this = $(e.currentTarget),
            id = $this.attr('data-target').slice(1);
        
        $.get(options.url, function (modalHtml) {
          $('<div class="modal fade" id="' + id + '" role="dialog" aria-hidden="true">'+ modalHtml +'</div>').modal().on('hidden.bs.modal', function (e) {
            return $(e.currentTarget).remove();
          }).on('shown.bs.modal', function () {
            return $this.trigger('shown.modal');
          });
        });
        
        $(document).on("shown.bs.modal", "#"+id, function(e){
          var $form = $(e.currentTarget).find("form")
          bindSubmit($form);
          resetSearch($form);
        })
        
      });
    }
    
    // 绑定表单事件
    function bindSubmit($form) {
      $form.on('click', '[type="submit"]', function(e) {
        e.preventDefault();
        if(e.target != e.currentTarget) return
        if(!options.beforeSubmit || options.beforeSubmit.call(this, el)) {
          $(e.target).attr('disabled', 'disabled')
          ajaxCall($form);
        }
      })
    }
    
    // 重置查询结果
    function resetSearch($form) {
      $("button[name='reset']").on("click", function(e){
        $form.find('input[data-validate],select[data-validate],textarea[data-validate]').each(function(){
          console.log(this);
          if(!$(this).attr("type") === 'hidden') {
            $(this).val('');
          }
        })
        
        $form.find(".koala-search-modal-message").remove();
        $form.find(".koala-modal-search-result-warp").remove();
        
      })
    }
    
    // 处理查询结果
    function handleSearchResponse($form, message, style, callback) {
      
      $form.find(".koala-search-modal-message").remove();
      $form.prepend('<p class="koala-search-modal-message text-center '+ style +'">' + message + '</p>')
      
      setTimeout(function(){
        $form.find(".koala-search-modal-message").remove();
      }, 3000)
      
      if(callback && typeof callback === 'object') {
        callback(el, $backdrop[0], message)
      }
      
      setTimeout(function(){
        $form.find('[type="submit"]').attr("disabled", false);
      }, 1000)
    }
    
    function handleTableTemplate($form, data, page) {
      
      var $dataTemplate = '<div class="koala-modal-search-result-warp clearfix"><div style="height: 200px; overflow: auto;"><table class="table table-hover ms-table" style="margin-bottom: 4px;"><thead><tr>';
      
      $dataTemplate = $dataTemplate + '<th></th>';
      
      for(var i in options.tableColumns) {
        $dataTemplate = $dataTemplate + '<th class="text-center">' + options.tableColumns[i] + '</th>';
      }
      
      $dataTemplate = $dataTemplate + '</tr></thead><tbody>';
      
      var valueString = '';
      
      for(var i in data) {
        $dataTemplate = $dataTemplate + '<tr>';
        
        var radioValue = ''
        for(var j in options.values) {
          radioValue = radioValue + ( ((parseInt(j)+1) == options.values.length) ? data[i][options.values[j]] : (data[i][options.values[i]] + ' - '));
        }
        
        var radioDisplay = '';
        for(var l in options.displayValues) {
          radioDisplay = radioDisplay + ((parseInt(l)+1) == options.displayValues.length ? data[i][options.displayValues[l]] : (data[i][options.displayValues[l]] + ' - '))
        }
        
        $dataTemplate = $dataTemplate + '<td><input type="radio" name="modal-search-radio" value="'+radioValue+'" data-display="'+radioDisplay+'"></td>';
        
        for(var k in options.tableValues) {
          $dataTemplate = $dataTemplate + '<td>' +  data[i][options.tableValues[k]]  + '</td>';
        }
        
        $dataTemplate = $dataTemplate + '</tr>';
      }
      
      $dataTemplate = $dataTemplate + '</body></table></div>';
      
      if(page !== undefined) {
        
        var nextPage = parseInt(page.currentPage) + 1;
        var prePage = parseInt(page.currentPage) - 1;
        
        $dataTemplate = $dataTemplate + '<div class="">';
        $dataTemplate = $dataTemplate + '<div class=""><ul class="pagination ms-pagination no-margin clearfix">';
        
        if(page.prePage) {
          $dataTemplate = $dataTemplate +'<li><a href="javascript:void(0);" data-page="1"><i class="glyphicon glyphicon-step-backward"></i></a></li>';
          $dataTemplate = $dataTemplate +'<li><a href="javascript:void(0);" data-page="'+ prePage +'"><i class="glyphicon glyphicon-chevron-left"></i></a></li>';
        }
        
        if(page.totalPage !== undefined && page.totals != undefined) {
          $dataTemplate = $dataTemplate + '<li><p>' + page.currentPage + '/' + page.totalPage + '页，共' + page.totals + '条记录</p></li>';
        }
        
        if(page.nextPage) {
          $dataTemplate = $dataTemplate + '<li><a href="javascript:void(0);" data-page="'+ nextPage + '"><i class="glyphicon glyphicon-chevron-right"></i></a></li>';
          $dataTemplate = $dataTemplate + '<li><a href="javascript:void(0);" data-page="'+ page.totalPage + '"><i class="glyphicon glyphicon-step-forward"></i></a></li>';
        }
        
        if(page.totalPage > 1) {
          $dataTemplate = $dataTemplate + '<li><div class="paging-jump"><span>跳转到</span><input name="inputPage" data-total = "'+page.totalPage+'" /><button class="btn btn-default ajax-go-btn">Go</button>'
        }
        
        $dataTemplate = $dataTemplate + '</ul></div>';
      }
      
      $dataTemplate = $dataTemplate + '</div>';
      
      $form.find(".koala-modal-search-result-warp").remove();
      $form.append($dataTemplate);
      
      $(".koala-modal-search-result-warp td").on("click", function(){
        var $radio = $(this).parent().find("input[type='radio']");
        $radio.prop("checked", true)
        var value = $radio.val();
        var display = $radio.data("display");
        
        var modalId = $form.parents(".modal").attr("id");
        $("[data-modal-search='#"+modalId+"']").val(display);
        $("[data-modal-search='#"+modalId+"']").next().val(value);
        $("#"+modalId).modal('hide');
      })
      
      $(".koala-modal-search-result-warp .pagination a").on("click", function(){
        var pageValue = parseInt($(this).data("page"));
        $form.find("input[name='page']").remove();
        $form.prepend("<input type='hidden' name='page' value = '"+ pageValue +"'>");
        $form.find("button[type='submit']").trigger("click");
      })
      
      $(".koala-modal-search-result-warp input[name='inputPage']").on("change", function(){
        var value = parseInt($(this).val());
        var total = parseInt($(this).data("total"));
        if(value > total) {
          $(this).val('');
        }
      })
      
      $(".koala-modal-search-result-warp .pagination .ajax-go-btn").on("click", function(e){
        e.preventDefault();
        var $input = $(this).parent().find("input");
        var pageValue = parseInt($($input).val());
        $form.find("input[name='page']").remove();
        $form.prepend("<input type='hidden' name='page' value = '"+ pageValue +"'>");
        $form.find("button[type='submit']").trigger("click");
      })
      
    }
    
    // 提交表单
    function ajaxCall($form) {
      var parameters = $form.serializeArray();
      $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: parameters
      }).done(function(response) {
        
        response = typeof response === 'string' ? JSON.parse(response) : response
        
        if(parseInt(response.code) == 0) {  
          
          setTimeout(function(){
            
            handleTableTemplate($form, response.data.list, response.data.page);
            
            $form.find('[type="submit"]').attr("disabled", false);
          }, 300)
          
        } else {
          handleSearchResponse($form, response.message || options.failureMessage, "text-danger", options.failure);
        }
      }).fail(function() {
        handleSearchResponse($form, options.errorMessage, "text-danger");
      })
    }
  }

  $.fn.modalsearch.noConflict = function() {
    $.fn.modalsearch = old
    return this
  }

})
